package com.bootadmin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bootadmin.core.config.QiniuConfig;
import com.bootadmin.core.utils.DateUtils;
import com.bootadmin.core.web.FileResponse;
import com.bootadmin.service.QiniuService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * @author kongzm
 * @description: 七牛服务实现
 * @date 2022/7/9 16:28
 */
@Service
public class QiniuServiceImpl implements QiniuService {
    private final Logger logger = LoggerFactory.getLogger(QiniuServiceImpl.class);

    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private QiniuConfig qiniuConfig;

    @Override
    public FileResponse upload(String projectName, String fileName, InputStream inputStream) {
        FileResponse fileResponse = new FileResponse();
        try {
            String key = qiniuConfig.getEnv() + "/" + projectName + "/" +
                    DateUtils.formatDate(System.currentTimeMillis(), "yyyyMMdd") + "/" +
                    fileName;
            Response response = uploadManager.put(inputStream, key, getToken(), null, null);
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);

            fileResponse.setFileUrl(qiniuConfig.getDomain() + "/" + putRet.key);
            return fileResponse;
        } catch (QiniuException e) {
            Response r = e.response;
            logger.error(r.toString());
            try {
                logger.error(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }

            fileResponse.setSuccess(false);
            fileResponse.setMsg("上传失败：" + r.toString());
        }

        return fileResponse;
    }

    private String getToken() {
        Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
        return auth.uploadToken(qiniuConfig.getBucket());
    }
}
